﻿Imports System.Reflection
Imports System.Collections.ObjectModel

Public Class Workspace
    Inherits Canvas
    Public Sub New()

    End Sub
    Public Sub New(ByVal name As String)
        WorkspaceName = name
    End Sub
    Private Sub Workspace_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        HorizontalAlignment = Windows.HorizontalAlignment.Stretch
        VerticalAlignment = Windows.VerticalAlignment.Stretch
        Background = New SolidColorBrush(My.Application.WorkspaceBackgroundColor) ' New SolidColorBrush(ColorConverter.ConvertFromString("#FF5F5F5F")) ' Color.FromArgb(100, 255, 0, 255))
    End Sub

    Public Property WorkspaceName As String = "workspace1"
    Public Property WorkspaceDescription As String = ""
    Public Property FilePath As String
    Public Function Closing(askToSave As Boolean) As Boolean
        If askToSave Then
            Dim result As Integer = ShowInfoBox("Save workspace '" & WorkspaceName & "'?", GetFirstParentOfType(Me, GetType(Window)), "Yes", "No", "Cancel")
            If result = 0 Then
                Save()
            ElseIf result = 2 Then
                Return False
            End If
        Else
            Save()
        End If
        Return True
    End Function
    Public Function LoadFromFile(ByVal filename As String) As Boolean

        FilePath = filename
        WorkspaceName = ReadSetting(FilePath, "WorkspaceName", WorkspaceName)
        WorkspaceDescription = CStr(ReadSetting(FilePath, "WorkspaceDescription", WorkspaceDescription.Replace(vbNewLine, Chr(1)))).Replace(Chr(1), vbNewLine)
        Dim chartNames() As String = Split(ReadSetting(FilePath, "Charts", ""), ",")
        'Dim box = ShowInfoBoxAsync("Loading workspace '" & WorkspaceName & "'...")
        For Each item In chartNames
            If item <> "" Then
                If IsNumeric(item) Then
                    Dim chart As New Chart
                    chart.ChartOverrideTickerID = item
                    Children.Add(chart)
                Else
                    ShowInfoBox("'" & WorkspaceName & "' is an outdated workspace and cannot be loaded.", GetFirstParentOfType(Me, GetType(Window)))
                    Return False
                End If
            End If
        Next
        'box.Close()
        OrderCharts()
        Return True
    End Function
    Public Sub Save()
        'IO.File.Create(AppDomain.CurrentDomain.BaseDirectory & WORKSPACE_FOLDER_WITH_SLASH & WorkspaceName & ".ws")
        If FilePath = "" Then FilePath = AppDomain.CurrentDomain.BaseDirectory & WORKSPACE_FOLDER_WITH_SLASH & WorkspaceName & ".ws"
        File.WriteAllText(FilePath, "")
        'Dim box = ShowInfoBoxAsync("Saving workspace '" & WorkspaceName & "'...")
        For Each Chart In Children
            If TypeOf Chart Is Chart Then
                CType(Chart, Chart).SaveSettings()
            End If
        Next
        Dim names As New List(Of String)
        For Each item In Children
            If TypeOf item Is Chart Then
                names.Add(CType(item, Chart).GetChartName)
            End If
        Next
        WriteSetting(FilePath, "Charts", Join(names.ToArray, ","))
        WriteSetting(FilePath, "WorkspaceName", WorkspaceName)
        WriteSetting(FilePath, "WorkspaceDescription", WorkspaceDescription.Replace(vbNewLine, Chr(1)))
        ' box.Close()
    End Sub

    Public ReadOnly Property SelectedChart As Chart
        Get
            For Each item In Children
                If TypeOf item Is Chart AndAlso CType(item, Chart).IsSelected Then Return CType(item, Chart)
            Next
            Return Nothing
        End Get
    End Property
    Public ReadOnly Property Charts As ReadOnlyCollection(Of Chart)
        Get
            Dim returnVal As New List(Of Chart)
            For Each child In Children
                If TypeOf child Is Chart Then returnVal.Add(child)
            Next
            Return New ReadOnlyCollection(Of Chart)(returnVal)
        End Get
    End Property

    Public Sub OrderCharts()

        Dim charts As List(Of Chart) = Me.Charts.ToList
        For i = 1 To charts.Count
            Dim minIndex As Integer = Integer.MaxValue
            Dim minChart As Chart = Nothing
            For Each chart In charts
                If Canvas.GetZIndex(chart) < minIndex Then
                    minIndex = Canvas.GetZIndex(chart)
                    minChart = chart
                End If
            Next
            Canvas.SetZIndex(minChart, i)
            charts.Remove(minChart)
        Next
    End Sub

    Friend Sub Command_Executed(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
        Dim selected As Chart = SelectedChart
        If e.Command Is ChartCommands.NewChart Then
            Dim chart As New Chart
            chart.Bounds = New Bounds(0, 0, 30, 30)
            Children.Add(chart)
        End If
    End Sub

    Protected Overrides Sub OnVisualChildrenChanged(ByVal visualAdded As System.Windows.DependencyObject, ByVal visualRemoved As System.Windows.DependencyObject)
        If visualAdded Is Nothing OrElse TypeOf visualAdded Is Chart Then
            If visualAdded IsNot Nothing Then CType(visualAdded, Chart).IsSelected = True
            MyBase.OnVisualChildrenChanged(visualAdded, visualRemoved)
        Else
            Throw New ArgumentException("Workspace children can only be charts.")
        End If
    End Sub
End Class
